package com.sh.demo.qa.module.rbac.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.sh.demo.qa.module.rbac.entity.Role;
import com.sh.demo.qa.module.rbac.entity.User;
import com.sh.demo.qa.module.rbac.service.UserService;

public class ShiroDbRealm extends AuthorizingRealm{

	protected final static Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);

	@Autowired
	private UserService userService;
	
	/**
	 * 登录认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		
		UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
		User user = userService.findByCode(token.getUsername());
		if (user != null) {
			return new SimpleAuthenticationInfo(user.getCode(), user.getPassword(), getName());
		} else {
			return null;
		}
	}
	
	/**
	 * 访问授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		// 认证时候存入的Principal对象
		String userCode = (String) principals.getPrimaryPrincipal(); 
		User user = userService.findByCode(userCode);
		if(user != null){
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			for (Role role : user.getRoles()) {
				// 角色信息
				info.addRole(role.getName()); 
				// 权限信息
//				info.addStringPermissions(role.getPermissionCodes());
			}
			return info;
		}else{
			return null;
		}
	}

}
